package com.luo.chengrui.module.sa.service.org;


import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.exception.ServerException;
import com.luo.chengrui.module.sa.controller.admin.org.vo.OrgExportReqVO;
import com.luo.chengrui.module.sa.dal.dataobject.org.OrgDO;
import com.luo.chengrui.module.sa.dal.dataobject.person.PersonDO;
import com.luo.chengrui.module.sa.dal.dataobject.person.PersonSyncDO;
import com.luo.chengrui.module.sa.dal.mysql.org.OrgMapper;
import com.luo.chengrui.module.sa.dal.mysql.person.PersonMapper;
import com.luo.chengrui.module.sa.enums.ErrorCodeConstants;
import com.luo.chengrui.module.sa.enums.OrgKindEnum;
import com.luo.chengrui.module.sa.service.person.PersonService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserCreateDTO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 组织人员同步
 */
@Service
public class OrgAndPersonSyncServiceImpl implements OrgAndPersonSyncService {
    @Resource
    OrgMapper orgMapper;
    @Resource
    PersonMapper personMapper;

    @Resource
    AdminUserApi adminUserApi;
    @Resource
    DeptApi deptApi;


    @Override
    public void deleteOrg(Long id) {
        deptApi.deleteDept(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orgSync(OrgDO orgDO) {
        if (OrgKindEnum.Org.getCode().equalsIgnoreCase(orgDO.getOrgKindId())
                || OrgKindEnum.Dept.getCode().equalsIgnoreCase(orgDO.getOrgKindId())
                || OrgKindEnum.Center.getCode().equalsIgnoreCase(orgDO.getOrgKindId())
        ) {
            DeptRespDTO dept = new DeptRespDTO();
            if (com.luo.chengrui.module.sa.service.org.OrgService.ORG_ROOT_ID.equals(orgDO.getParentId())) {
                dept.setParentId(0L);
            } else {
                OrgDO parentOrg = orgMapper.selectById(orgDO.getParentId());
                if (Objects.isNull(parentOrg.getSystemId())) {
                    throw new ServerException(ErrorCodeConstants.ORG_PARENT_NOT_SYNC);
                }
                dept.setParentId(parentOrg.getSystemId());
            }

            dept.setName(orgDO.getName());
            dept.setSort(orgDO.getSequence());
            dept.setStatus(orgDO.getStatus());

            if (Objects.isNull(orgDO.getSystemId())) {
                Long id = deptApi.createDept(dept);
                OrgDO updateDO = new OrgDO();
                updateDO.setId(orgDO.getId());
                updateDO.setSystemId(id);
                orgMapper.updateById(updateDO);
            } else {
                dept.setId(orgDO.getSystemId());
                deptApi.updateDept(dept);
            }
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orgSync() {
        // 查询所有sa_oporg组织数据。
        OrgExportReqVO reqVO = new OrgExportReqVO();
        reqVO.setOrgKindIds(String.format("%s,%s,%s", OrgKindEnum.Org.getCode(), OrgKindEnum.Dept.getCode(), OrgKindEnum.Center.getCode()));
        List<OrgDO> orgList = orgMapper.selectList(reqVO);
        List<OrgTreeVo> orgTreeList = orgList.stream().map(orgDO -> new OrgTreeVo(orgDO)).collect(Collectors.toList());
        List<OrgTreeVo> collect = orgTreeList.stream().filter(m -> Objects.equals(m.getOrgDO().getParentId(), OrgService.ORG_ROOT_ID)).map(
                (m) -> {
                    m.setChildren(getChildrenList(m, orgTreeList));
                    return m;
                }
        ).collect(Collectors.toList());

        List<OrgDO> updateOrgList = new ArrayList<>();
        for (OrgTreeVo org : collect) {
            sync2SystemDept(0L, org, updateOrgList);
        }

        if (updateOrgList.size() > 0) {
            orgMapper.updateBatch(updateOrgList);
        }

    }

    private void sync2SystemDept(Long parentId, OrgTreeVo org, List<OrgDO> updateOrgList) {
        if (org.getOrgDO().getSystemId() == null || org.getOrgDO().getSystemId() == 0L) {
            // TODO 插入
            DeptRespDTO dept = new DeptRespDTO();
            dept.setName(org.getOrgDO().getName());
            dept.setParentId(parentId);
            dept.setSort(org.getOrgDO().getSequence());
            dept.setStatus(org.getOrgDO().getStatus());
            Long id = deptApi.createDept(dept);
            org.getOrgDO().setSystemId(id);
            updateOrgList.add(org.getOrgDO());
        }

        if (org.getChildren() != null && org.getChildren().size() > 0) {
            for (OrgTreeVo child : org.getChildren()) {
                sync2SystemDept(org.getOrgDO().getSystemId(), child, updateOrgList);
            }
        }
    }

    /**
     * 获取子节点列表
     *
     * @param tree
     * @param list
     * @return
     */
    public List<OrgTreeVo> getChildrenList(OrgTreeVo tree, List<OrgTreeVo> list) {
        List<OrgTreeVo> children = list.stream().filter(item -> Objects.equals(item.getOrgDO().getParentId(), tree.getOrgDO().getId())).map(
                (item) -> {
                    item.setChildren(getChildrenList(item, list));
                    return item;
                }
        ).collect(Collectors.toList());
        return children;
    }


    class OrgTreeVo {
        private OrgDO orgDO;
        private List<OrgTreeVo> children;

        public OrgTreeVo(OrgDO orgDO) {
            this.orgDO = orgDO;
        }

        public OrgDO getOrgDO() {
            return orgDO;
        }

        public void setOrgDO(OrgDO orgDO) {
            this.orgDO = orgDO;
        }

        public List<OrgTreeVo> getChildren() {
            return children;
        }

        public void setChildren(List<OrgTreeVo> children) {
            this.children = children;
        }
    }

    @Override
    public void personSync() {
        List<PersonSyncDO> personList = personMapper.selectSyncList();
        List<OrgDO> updateList = new ArrayList<>();
        for (PersonSyncDO person : personList) {
            if (person.getSystemUserId() == null || person.getSystemUserId() == 0L) {
                AdminUserCreateDTO userCreateDTO = new AdminUserCreateDTO();
                userCreateDTO.setDeptId(person.getSystemDeptId());
                userCreateDTO.setPassword(PersonService.DEFAULT_PASSWORD);
                userCreateDTO.setUsername(person.getLoginName());
                userCreateDTO.setNickname(person.getName());
                Long id = adminUserApi.createUser(userCreateDTO);
                person.setSystemUserId(id);
                PersonDO personUpdateDo = new PersonDO();
                personUpdateDo.setId(person.getId());
                personUpdateDo.setSystemUserId(id);
                personMapper.updateById(personUpdateDo);

                OrgExportReqVO exportReqVO = new OrgExportReqVO();
                exportReqVO.setPersonId(person.getId());
                // 查询用户所有岗位信息
                List<OrgDO> psmOrgList = orgMapper.selectList(exportReqVO);
                if (CollUtil.isNotEmpty(psmOrgList)) {
                    psmOrgList.stream().forEach(item -> {
                        item.setSystemId(person.getSystemUserId());
                    });
                    updateList.addAll(psmOrgList);
                }
            }
        }
        if (CollUtil.isNotEmpty(updateList)) {
            orgMapper.updateBatch(updateList);
        }
    }


    @Override
    public void personSync(PersonDO person) {
        OrgExportReqVO exportReqVO = new OrgExportReqVO();
        exportReqVO.setPersonId(person.getId());
        // 查询用户所有岗位信息
        List<OrgDO> psmOrgList = orgMapper.selectList(exportReqVO);
        AdminUserCreateDTO userCreateDTO = new AdminUserCreateDTO();

        if (!Objects.isNull(person.getMainOrgId())) {
            // 过滤出主岗位
            List<OrgDO> mainPsmOrg = psmOrgList.stream().filter(orgDO -> Objects.equals(orgDO.getParentId(), person.getMainOrgId())).collect(Collectors.toList());
            if (Objects.isNull(mainPsmOrg) || mainPsmOrg.size() == 0) {
                throw new ServerException(ErrorCodeConstants.ORG_PARENT_NOT_EXISTS);
            }
            OrgDO mainPsm = mainPsmOrg.get(0);
            // 查询部门信息
            OrgDO deptOrg = orgMapper.selectById(mainPsm.getDeptId());
            userCreateDTO.setDeptId(deptOrg.getSystemId());
        }

        userCreateDTO.setPassword(PersonService.DEFAULT_PASSWORD);
        userCreateDTO.setUsername(person.getLoginName());
        userCreateDTO.setNickname(person.getName());
        userCreateDTO.setStatus(person.getStatus());
        if (Objects.isNull(person.getSystemUserId())) {
            Long id = adminUserApi.createUser(userCreateDTO);
            person.setSystemUserId(id);
            PersonDO personUpdateDO = new PersonDO();
            personUpdateDO.setId(person.getId());
            personUpdateDO.setSystemUserId(id);
            personMapper.updateById(personUpdateDO);
        } else {
            userCreateDTO.setId(person.getSystemUserId());
            adminUserApi.updatePerson(userCreateDTO);
        }
        //更新sa_org表中psm 的systemDeptId。
        exportReqVO = new OrgExportReqVO();
        exportReqVO.setPersonId(person.getId());
        // 查询用户所有岗位信息
        psmOrgList = orgMapper.selectList(exportReqVO);
        if (CollUtil.isNotEmpty(psmOrgList)) {
            psmOrgList.stream().forEach(item -> {
                item.setSystemId(person.getSystemUserId());
            });
            orgMapper.updateBatch(psmOrgList);
        }
    }

    @Override
    public void deletePerson(Long id) {
        adminUserApi.deletePerson(id);
    }
}
